import logging
import re

from rest_framework import serializers
from tsukkomi.models import Tsukkomi, Comment, TsukkomiCollect, TsukkomiLike, CommentLike

logger = logging.getLogger("django")


class TsukkomiListSerializer(serializers.ModelSerializer):
    """吐槽内容的序列化器"""
    like_count = serializers.IntegerField(default=0, label="点赞数量")
    is_collect = serializers.BooleanField(label="是否收藏", default=False)

    class Meta:
        model = Tsukkomi
        fields = ("id", "content", "create_time", "like_count", "is_collect", "url")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
        }


class TsukkomiInfoSerializer(serializers.ModelSerializer):
    """吐槽详情的序列化器"""
    like_count = serializers.IntegerField(default=0, label="点赞数量")
    comment_count = serializers.IntegerField(default=0, label="评论数量")
    user = serializers.StringRelatedField(read_only=True, label="用户名")  # 显示用户名而不是用户id

    class Meta:
        model = Tsukkomi
        fields = ("id", "content", "create_time", "like_count", "share_count", "comment_count", "user", "image_url")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
        }


class TsukkomiSonCommentSerializer(serializers.ModelSerializer):
    """自评论序列化器"""
    user = serializers.StringRelatedField(read_only=True, label="用户名")  # 显示用户名而不是用户id

    class Meta:
        model = Comment
        fields = ("id", "message", "create_time", "user", "parent")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
        }


class TsukkomiCommentSerializer(serializers.ModelSerializer):
    """获取主评论序列化器"""
    user = serializers.StringRelatedField(read_only=True, label="用户名")  # 显示用户名而不是用户id
    like_count = serializers.IntegerField(default=0, label="点赞数量")
    son_comments = TsukkomiSonCommentSerializer(many=True)

    class Meta:
        model = Comment
        fields = ("id", "message", "create_time", "like_count", "user", "son_comments")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
        }


class CreationCommentSerializer(serializers.ModelSerializer):
    """创建评论信息"""
    user = serializers.StringRelatedField(read_only=True, label="用户名")  # 显示用户名而不是用户id

    class Meta:
        model = Comment
        fields = ("message", "parent", "tsukkomi", "create_time", "user")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
        }

    def validate_message (self, data):
        print(data)
        if not data:
            raise serializers.ValidationError("消息不存在")
        return data

    def validate (self, attrs):
        print(attrs)
        parent_obj = attrs.get("parent", None)  # 获取parent id
        if parent_obj:
            if not Comment.objects.get(id=parent_obj.id):
                raise serializers.ValidationError("父评论不存在")
            return attrs
        return attrs

    def create (self, validated_data):
        print(validated_data)
        user = self.context["request"].user
        message = validated_data["message"]
        parent = validated_data["parent"]
        tsukkomi = validated_data["tsukkomi"]

        # 创建数据
        comment = Comment.objects.create(message=message, user=user, parent=parent, tsukkomi=tsukkomi)
        return comment


class CreationTsukkomiSerializer(serializers.ModelSerializer):
    """创建吐槽信息"""
    like_count = serializers.IntegerField(default=0, label="点赞数量", read_only=True)
    comment_count = serializers.IntegerField(default=0, label="评论数量", read_only=True)
    user = serializers.StringRelatedField(read_only=True, label="用户名")  # 显示用户名而不是用户id

    class Meta:
        model = Tsukkomi
        fields = ("id", "content", "create_time", "like_count", "share_count", "comment_count", "user", "image_url")
        extra_kwargs = {
            'create_time': {
                "read_only": True,
            },
            "share_count": {
                "read_only": True,
            },
        }

    def validate_content (self, data):
        if data is None:
            raise serializers.ValidationError("吐槽内容为空")
        return data

    def create (self, validated_data):
        user = self.context["request"].user
        tsukkomi = Tsukkomi.objects.create(content=validated_data["content"], user_id=user.id)
        # 添加图片url和content重构
        content_data = tsukkomi.content
        try:
            image_url = re.findall(r"<img.*?src=[\"](.*?)[\"].*?/>", content_data)[0]  # 提取图片链接
        except Exception as e:
            logger.error(e)
            content = re.sub(r"<[^>]*>", "", content_data)  # 过滤后的内容
            tsukkomi.content = content
            tsukkomi.save()
            return tsukkomi

        tsukkomi.image_url = image_url
        content = re.sub(r"<[^>]*>", "", content_data)  # 过滤后的内容
        tsukkomi.content = content
        tsukkomi.save()
        return tsukkomi


class TsukkomiCollectSerializer(serializers.ModelSerializer):
    """收藏与点赞吐槽"""

    class Meta:
        model = TsukkomiCollect
        fields = ("id", "tsukkomi", "user",)
        extra_kwargs = {
            'user': {
                "read_only": True,
            }
        }

    def validate (self, attrs):
        if not Tsukkomi.objects.get(id=attrs["tsukkomi"].id):
            raise serializers.ValidationError("吐槽内容不存在")
        return attrs

    def create (self, validated_data):
        user_id = self.context["request"].user.id
        request = self.context["request"]
        request_url = request.path_info  # 根据请求的url 决定是点赞还是收藏
        if request_url == "/like/tsukkomi/":
            if not request.COOKIES.get("like_tsukkomi_" + str(validated_data["tsukkomi"].id)):
                tsukkomi = TsukkomiLike.objects.create(tsukkomi=validated_data["tsukkomi"], user_id=user_id)
            else:
                raise serializers.ValidationError({"message": "请勿重复点赞"})
        else:
            tsukkomi = TsukkomiCollect.objects.create(tsukkomi=validated_data["tsukkomi"], user_id=user_id)
        return tsukkomi


class CommentLikeSerializer(serializers.ModelSerializer):
    """评论点赞序列化器"""

    class Meta:
        model = CommentLike
        fields = ("id", "comment", "user",)
        extra_kwargs = {
            'user': {
                "read_only": True,
            }
        }

    def validate (self, attrs):
        if not Comment.objects.get(id=attrs["comment"].id):
            raise serializers.ValidationError("此评论不存在")
        return attrs

    def create (self, validated_data):
        user_id = self.context["request"].user.id
        request = self.context["request"]
        if not request.COOKIES.get("like_comment_" + str(validated_data["comment"].id)):
            comment = CommentLike.objects.create(comment=validated_data["comment"], user_id=user_id)
            return comment
        else:
            raise serializers.ValidationError({"message": "请勿重复点赞"})
